# Create your views here.
from django.http import HttpResponse, Http404
from django.template import RequestContext
from django.template.loader import get_template
from django.contrib.auth.models import User
from django.template import TemplateDoesNotExist
from django.views.defaults import page_not_found
from frontend.models import *
import MySQLdb
import math
from django.http import HttpResponseRedirect
from django.contrib.auth import logout 
import bookstore.settings
rootPath = bookstore.settings.ROOT_PATH
var_featured = ''
var_category = ''
var_famous = ''
var_newbook = ''
var_check = 0
var_check2 = ''
var_category_page = ''
categoryName = ''
var_check_string = ''
var_special = ''
var_book = ''
var_book_detail = ''
loged = ''
var_check_email = ''
var_getstatus_email = 0

var_static_aboutus = getAboutUsStatic()
var_static_aboutourstore = getAboutOurStoreStatic()
var_static_service = getServiceStatic()
var_static_privacy = getPrivacyStatic()
def main_page(request):
  check_loged(request)
  view_featured()
  view_all_page()
  view_newbook()
  template = get_template('home_page.html')
  return return_request(template, request)

def home_page(request):
    check_loged(request)
    view_featured()
    view_all_page()
    view_newbook()
    template = get_template('home_page.html')
    return return_request(template, request)
    
def view_featured():
    global var_featured
    var_featured = ""
    rows = getFeaturedBook()
    for row in rows:
        image_location = rootPath + '/site_media/frontend/images/thumbnail/' + row[1]
        summary = row[2]
        like = row[3]
        id = row[4]
        link = rootPath + '/book/detail/%s' % (id)
        var_featured += '<div class="feat_prod_box">\n\
            <div class="prod_img">\n\
                    <a href="%s"><img\n\
                    src="%s" alt="" title="" border="0" class="size150"/>\n\
                    </a>\n\
            </div>\n\
            <div class="prod_det_box">\n\
            <div class="box_top"></div>\n\
            <div class="box_center">\n\
                <div class="prod_title">%s</div>\n\
                <p class="details">%s</p>\n\
                <div class="pluginHome">\n\
                                <div class="eachPlugin" id="like"></div>\n\
                                <div class="number">%s</div>\n\
                        </div>\n\
                <a href="%s" class="more">- more details -</a>\n\
                <div class="clear"></div>\n\
            </div>\n\
            <div class="box_bottom"></div>\n\
            </div>\n\
            <div class="clear"></div>\n\
            </div>\n\
        ' % (link, image_location, row[0], summary, like, link)
    return
    

    
def view_newbook():
    global var_newbook
    var_newbook = ""
    rows = getNewBook()
    for row in rows:
        id = row[2]
        link = rootPath + '/book/detail/%s' % (id)
        image_location = rootPath + '/site_media/frontend/images/thumbnail/' + row[1]
        var_newbook += '<div class="new_products">\n\
        <div class="new_prod_box">\n\
        <a class="ellipsis" id="ellipsis" title="" href="%s">%s</a>\n\
        <div class="new_prod_bg">\n\
        <span class="special_icon"><img src="/site_media/frontend/images/new_icon.gif" alt="" title="" /></span>\n\
        <a href="%s" class="preview" title="">\n\
        <img src="%s" alt="" class="thumb" border="0" /> \n\
        </a>\n\
        </div>\n\
        </div>\n\
        </div>\n\
        ' % (link, row[0], link, image_location)
    return
    
def view_category():
    global var_category
    var_category = ''    
    rows = getCategoryBook()    
    for row in rows:
        link = row[0]
        var_category += '<li><a href="%s/category/%s">%s</a></li>' % (rootPath, row[0], row[1])        
    return


def view_category_page(id):
    global var_category_page
    global categoryName    
    var_category_page = ''       
    categoryName = getCategoryName(id)
    rows = getBook_category(id)    
    i = 0
    for row in rows:
        link = rootPath + '/book/detail/%s' % (row[5])
        temp = ''        
        if(row[3] == 1):
            temp = '<span class="special_icon"><img src="/site_media/frontend/images/special_icon.gif" alt="" title="" /></span>'
        elif (i < 1):
            temp = '<span class="special_icon"><img src="/site_media/frontend/images/new_icon.gif" alt="" title="" /></span>'
        image_location = rootPath + '/site_media/frontend/images/thumbnail/' + row[0]
        var_category_page += '<div class="new_products">\n\
        <div class="new_prod_box">\n\
        <a class="ellipsis" id="ellipsis" title="" href="">%s</a>\n\
        <div class="new_prod_bg">\n\
        %s\n\
        <a href="%s" class="preview" title="">\n\
        <img src="%s" alt="" class="thumb" border="0" /> \n\
        </a>\n\
        </div>\n\
        </div>\n\
        </div>\n\
        ' % (row[1], temp, link, image_location)
        i += 1
    return
        
def view_famous():
    global var_famous
    var_famous = ''
    rows = getFamousBook()
    i = 0
    for row in rows:
        i += 1
        title = row[0]
        thumbnail = row[1]
        author = row[2]
        like = row[3]
        price = row[4]
        point = row[5]
        id = row[6]
        link = rootPath + '/book/detail/%s' % (id)
        image_location = rootPath + '/site_media/frontend/images/thumbnail/' + thumbnail
        var_famous += '<div class="element">\n\
                <span class="image_text">#%s</span>\n\
                <div class="image_top">\n\
                    <img src="/site_media/frontend/images/top.png" width="30px" style="margin: -2px 0px 0px 10px;" alt="" title="" class="thumb" border="0"/>\n\
                </div>\n\
                <div class="image">\n\
                    <a href="%s">\n\
                    <img src="%s" width="60px" height="100px" class="thumb" border="0"/> </a>\n\
                </div>\n\
                <div class="content">\n\
                    <a href="%s">\n\
                    <li class="bookname">%s</li></a>\n\
                    <li class="bookname">Author: Group 4</li>\n\
                    <li>Like: %s</li>\n\
                    <li>Price: %s $</li>\n\
                    <li class="point">Point: %s</li>\n\
                </div>\n\
            </div>\n\
            ' % (i, link, image_location, link, title, like, price, point)
    return


def view_special(page):
    global var_special
    global var_check
    var_special = ""
    rows = getSpecialBook()
    len = 0
    for row in rows:
        len += 1
    specialPageSize = getSpecialPageSize()
    specialPageSize1 = int(specialPageSize)
    specialPageSize2 = float(specialPageSize)
    numberofpage = int(math.ceil(len / specialPageSize2))
    for i in range ((page - 1) * specialPageSize1, page * specialPageSize1):
        if i >= len:
            break 
        row = rows[i]
        image_location = rootPath + '/site_media/frontend/images/thumbnail/' + row[1]
        summary = row[2]
        like = row[3]
        id = row[4]
        link = rootPath + '/book/detail/%s' % (id)
        var_special += '<div class="feat_prod_box">\n\
            <div class="prod_img">\n\
                    <a href="%s"><img\n\
                    src="%s" alt="" title="" border="0" class="size150"/>\n\
                    </a>\n\
            </div>\n\
            <div class="prod_det_box">\n\
            <span class="special_icon"><img src="/site_media/frontend/images/special_icon.gif" alt="" title=""></span>\
            <div class="box_top"></div>\n\
            <div class="box_center">\n\
                <div class="prod_title">%s</div>\n\
                <p class="details">%s</p>\n\
                <div class="pluginHome">\n\
                                <div class="eachPlugin" id="like"></div>\n\
                                <div class="number">%s</div>\n\
                        </div>\n\
                <a href="%s" class="more">- more details -</a>\n\
                <div class="clear"></div>\n\
            </div>\n\
            <div class="box_bottom"></div>\n\
            </div>\n\
            <div class="clear"></div>\n\
            </div>\n\
        ' % (link, image_location, row[0], summary, like, link)
        
    if (len == 0 or numberofpage == 1):
        var_special += '<div class="pagination"> </div>'
    else :
        if(page == 1):
            var_special += '<div class="pagination"> <span class="disabled">[First]</span>\n '
            var_special += '<span class="disabled">&lt;&lt;</span>\n '
            for i in range (page, page + 3):
                if i <= numberofpage :
                    if i == page :
                        var_special += '<a href="%s/special/page%s"><span class="current">%s</span></a>\n' % (rootPath, i, i)
                    else :
                        var_special += '<a href="%s/special/page%s">%s</a>\n' % (rootPath, i, i)
            if i < numberofpage :
                var_special += '...'
            next = page + 1
            var_special += '<a href="%s/special/page%s"> &gt;&gt; </a>\n' % (rootPath, next)
            var_special += '<a href="%s/special/page%s"> [Last] </a>\n' % (rootPath, numberofpage);
            var_special += '</div>\n'
            
        elif page == numberofpage :
            previous = page - 1
            var_special += '<div class="pagination"> <a href="%s/special/page01">[First]</a>\n' % (rootPath)
            var_special += '<a href="%s/special/page%s">&lt;&lt;</a>\n' % (rootPath, previous)
            i = page - 2
            if i > 1 :
                var_special += '...'
            for i in range (page - 2 , numberofpage + 1):
                if i >= 1 :
                    if i == page :
                        var_special += '<a href="%s/special/page%s"><span class="current">%s</span></a>\n' % (rootPath, i, i)
                    else :
                        var_special += '<a href="%s/special/page%s">%s</a>\n' % (rootPath, i, i)
                        
            var_special += '<span class="disabled"> &gt;&gt; </span>\n'
            var_special += '<span class="disabled"> [Last] </span>\n'
            var_special += '</div>\n'
            
        else:
            previous = page - 1
            next = page + 1
            var_special += '<div class="pagination"> <a href="%s/special/page1">[First]</a>\n' % (rootPath)
            var_special += '<a href="%s/special/page%s">&lt;&lt;</a>\n' % (rootPath, previous)
            i = page
            for i in range (page - 1, page + 2) :
                if i <= numberofpage :
                    if i == page :
                        var_special += '<a href="%s/special/page%s"><span class="current">%s</span></a>\n' % (rootPath, i, i)
                    else :
                        var_special += '<a href="%s/special/page%s">%s</a>\n' % (rootPath, i, i)
            if i < numberofpage :
                var_special += '...'
            var_special += '<a href="%s/special/page%s"> &gt;&gt; </a>\n' % (rootPath, next)
            var_special += '<a href="%s/special/page%s"> [Last] </a>\n' % (rootPath, numberofpage)
            var_special += '</div>\n'
            
    return
    


def view_book(page):
    global var_book
    global var_check
    var_book = ""
    rows = getAllBook()
    len = 0
    for row in rows:
        len += 1
    numberofpage = int(math.ceil(len / 12.0))
    j = 0
    for i in range ((page - 1) * 12, page * 12):
        if i >= len:
            break 
        row = rows[i]
        id = row[4]
        link = rootPath + '/book/detail/%s' % (id)
        temp = ''   
        if(row[2] == 1):
            temp = '<span class="special_icon"><img src="/site_media/frontend/images/special_icon.gif" alt="" title="" /></span>\n'
        elif (j < 1):
            temp = '<span class="special_icon"><img src="/site_media/frontend/images/new_icon.gif" alt="" title="" /></span>\n'
        image_location = rootPath + '/site_media/frontend/images/thumbnail/' + row[0]
        var_book += '<div class="new_products">\n\
        <div class="new_prod_box">\n\
        <a class="ellipsis" id="ellipsis" title="" href="%s">%s</a>\n\
        <div class="new_prod_bg">\n\
        %s\n\
        <a href="%s" class="preview" title="">\n\
        <img src="%s" alt="" class="thumb" border="0" /> \n\
        </a>\n\
        </div>\n\
        </div>\n\
        </div>\n\
        ' % (link, row[1], temp, link, image_location)
        j += 1
        
    if (len == 0 or numberofpage == 1):
        var_book += '<div class="pagination"> </div>'
    else :
        if(page == 1):
            var_book += '<div class="pagination"> <span class="disabled">[First]</span>\n '
            var_book += '<span class="disabled">&lt;&lt;</span>\n '
            for i in range (page, page + 3):
                if i <= numberofpage :
                    if i == page :
                        var_book += '<a href="%s/book/page%s"><span class="current">%s</span></a>\n' % (rootPath, i, i)
                    else :
                        var_book += '<a href="%s/book/page%s">%s</a>\n' % (rootPath, i, i)
            if i < numberofpage :
                var_book += '...'
            next = page + 1
            var_book += '<a href="%s/book/page%s"> &gt;&gt; </a>\n' % (rootPath, next)
            var_book += '<a href="%s/book/page%s"> [Last] </a>\n' % (rootPath, numberofpage);
            var_book += '</div>\n'
            
        elif page == numberofpage :
            previous = page - 1
            var_book += '<div class="pagination"> <a href="%s/book/page01">[First]</a>\n' % (rootPath)
            var_book += '<a href="%s/book/page%s">&lt;&lt;</a>\n' % (rootPath, previous)
            i = page - 2
            if i > 1 :
                var_book += '...'
            for i in range (page - 2 , numberofpage + 1):
                if i >= 1 :
                    if i == page :
                        var_book += '<a href="%s/book/page%s"><span class="current">%s</span></a>\n' % (rootPath, i, i)
                    else :
                        var_book += '<a href="%s/book/page%s">%s</a>\n' % (rootPath, i, i)
                        
            var_book += '<span class="disabled"> &gt;&gt; </span>\n'
            var_book += '<span class="disabled"> [Last] </span>\n'
            var_book += '</div>\n'
            
        else:
            previous = page - 1
            next = page + 1
            var_book += '<div class="pagination"> <a href="%s/book/page1">[First]</a>\n' % (rootPath)
            var_book += '<a href="%s/book/page%s">&lt;&lt;</a>\n' % (rootPath, previous)
            i = page
            for i in range (page - 1, page + 2) :
                if i <= numberofpage :
                    if i == page :
                        var_book += '<a href="%s/book/page%s"><span class="current">%s</span></a>\n' % (rootPath, i, i)
                    else :
                        var_book += '<a href="%s/book/page%s">%s</a>\n' % (rootPath, i, i)
            if i < numberofpage :
                var_book += '...'
            var_book += '<a href="%s/book/page%s"> &gt;&gt; </a>\n' % (rootPath, next)
            var_book += '<a href="%s/book/page%s"> [Last] </a>\n' % (rootPath, numberofpage)
            var_book += '</div>\n'
            
    return


def view_book_detail(id):
    global var_book_detail
    var_book_detail = ''
    row = getBookFromId(id)
    thumbnail = row[0]
    author = row[1]
    summary = row[2]
    detail = row[3]
    title = row[4]
    location_small = rootPath + '/site_media/frontend/images/thumbnail/' + thumbnail
    location_large = rootPath + '/site_media/frontend/images/large/' + thumbnail
    var_book_detail += '<div class="title"><span class="title_icon"><img src="/site_media/frontend/images/bullet2.gif" alt="" title="" /></span>%s</div>\n\
                            <div class="feat_prod_box_details">            \n\
                   <div class="prod_img">\n\
                       <a href="">\n\
                       <img src="%s" alt="" title="" border="0" class="size150"/>\n\
                    </a>\n\
                  <br /><br />\n\
                  <a id="gallery" href="%s" title="%s">\n\
                    <img src="/site_media/frontend/images/zoom.gif" alt="" title="" border="0" />\n\
                  </a>\n\
                </div>\n\
              <div class="prod_det_box">\n\
                  <div class="box_top"></div>\n\
                  <div class="box_center">\n\
                      <div class="prod_title">Details</div>\n\
                      <p class="details">%s</p>             \n\
                      <div class="clear"></div>\n\
                  </div>\n\
                  <div class="box_bottom"></div>\n\
              </div>\n\
                <div class="clear"></div>\n\
            </div>\n\
            ' % (title, location_small, location_large, title, detail)
    var_book_detail += '<div id="tabvanilla" class="widget">\n\
            <ul class="tabnav">\n\
                <li><a href="#moreDetail">More details</a></li>\n\
                <li><a href="#relatedBook">Related books</a></li>\n\
                <li><a href="#comment">Comments</a></li>\n\
            </ul>\n\
            <div id="moreDetail" class="tabdiv">\n\
             <p>%s</p>\n\
            </div>\n\
            <div id="relatedBook" class="tabdiv">\n\
            ' % (detail)
    rows = getRelatedBook(id)
    for row in rows :
        relatedId = row[0]
        book = getBookForRelatedBox(relatedId)
        book_thumbnail = book[0]
        book_title = book[1]
        book_special = book[2]
        book_created = book[3]
        book_location = rootPath + '/site_media/frontend/images/thumbnail/' + book_thumbnail
        book_link = rootPath + '/book/detail/%s' % (relatedId)
        var_book_detail += '<div class="new_prod_box">\n\
                <a class="ellipsis" id="ellipsis" title="%s" href="%s">%s</a>    \n\
                <div class="new_prod_bg">\n\
                    <a href="%s" class="preview" title="%s">\n\
                        <img src="%s" alt="" class="thumb" border="0" /> \n\
                    </a>\n\
                </div>\n\
            </div > \n\
            ' % (book_title, book_link, book_title, book_link, book_title, book_location)
    var_book_detail += '<div class="clear"></div>    \n\
        </div>\n\
       <div id="comment" class="tabdiv">\n\
            <p>\n\
                Developping...\n\
            </p>\n\
        </div>\n\
        </div>\n\
    '
    return
    
def view_all_page():
    view_category()
    view_famous()

def return_request(template, request):
    variables = RequestContext(request, { 'var_check':var_check, 'rootPath': rootPath, 'var_featured': var_featured, 'var_newbook':var_newbook , 'var_category': var_category, 'var_famous':var_famous, 'var_check2':var_check2, 'var_category_page':var_category_page, 'categoryName':categoryName,
    'var_special':var_special, 'var_book':var_book, 'var_book_detail':var_book_detail, 'loged':loged, 'var_static_aboutus':var_static_aboutus
    , 'var_static_aboutourstore':var_static_aboutourstore, 'var_static_service':var_static_service, 'var_static_privacy':var_static_privacy, 'var_check_email':var_check_email
    , 'var_getstatus_email':var_getstatus_email})
    output = template.render(variables)
    return HttpResponse(output)
    

def logout_page(request):
    logout(request)
    return     HttpResponseRedirect('/')    

def login1_page(request):
    template = get_template('registration/login1.html')
    variables = RequestContext(request, { 'keke': "hihi" })
    output = template.render(variables)
    return HttpResponse(output)


def about_page(request):
    check_loged(request)
    view_all_page()
    template = get_template('about.html')
    return return_request(template, request)
    
def register_page(request):
    global var_check_email
    global var_getstatus_email
    check_loged(request)
    view_all_page()
    if request.method == "POST" :
        username = request.POST['username']    
        password = request.POST['password1']
        email = request.POST['email']
        phone = request.POST['phone']
        address = request.POST['address']
        company = request.POST['company']
        var_getstatus_email = sendEmail(username, email)
        if (var_getstatus_email == 0):
            var_check_email = '<h2> Thank you </h2>\n\
                            <h2> Register Successful </h2>'
            insertUserToDB(username, password, email)    
            insertUserInfo(username, phone, company, address)
            template = get_template('registersuccess.html')
            return return_request(template, request)
        elif (var_getstatus_email == 1):
            var_check_email = '<h2> Sorry ! </h2>\n\
                            <h2> Your email is invalid ! </h2>'
            template = get_template('registersuccess.html')
            return return_request(template, request)
    template = get_template('register.html')
    return return_request(template, request)
    

def error_page(request):
    view_all_page()
    template = get_template('error.html')
    return return_request(template, request)

def non_page(request):
    view_all_page()
    template = get_template('indexbase.html')
    return return_request(template, request)
    
def special_page(request):
    str = 'page01'
    return     HttpResponseRedirect(str)    
    
    
def special_page_pagging(request, page):
    currentpage = int(page)
    view_special(currentpage)
    view_all_page()
    template = get_template('special.html')
    return return_request(template, request)

def book_page_frontend(request):
    str = 'page01'
    return     HttpResponseRedirect(str)    
    
    
def book_page_pagging(request, page):
    check_loged(request)
    currentpage = int(page)
    view_book(currentpage)
    view_all_page()
    template = get_template('book.html')
    return return_request(template, request)
    
def contact_page(request):
    check_loged(request)
    global var_check2
    view_all_page()
    if request.method == "POST":
        name = request.POST['name']
        email = request.POST['email']
        phone = request.POST['phone']
        company = request.POST['company']
        message = request.POST['message']
        getContact_Info(name, email, phone, company, message)
        template = get_template('contact.html')
        var_check2 = "<B><I>CONTACT SUCCESSFUL !</I></B>"
        return return_request(template, request)
    template = get_template('contact.html')
    return return_request(template, request)    
    
def category_page(request, id):
    view_category_page(id)
    view_all_page()
    template = get_template('category_page.html')
    return return_request(template, request)
    
def book_detail_page(request, id):
    bookid = int(id)
    view_book_detail(bookid)
    view_all_page()
    template = get_template('detailbook.html')
    return return_request(template, request)

def check_loged(request):
    global loged
    loged = '<li><a href="%s/login">Sign in</a></li>' % (rootPath)
    user = request.user
    name = user.username
    if(name != ''):
        loged = '<li><a>Welcome,%s</a></li>' % (name)
        loged += '<li><a href="%s/logout">Logout</a></li>' % (rootPath)
    return
def services_page(request):
    view_all_page()
    template = get_template('services.html')
    return return_request(template, request)
    
def privacy_page(request):
    view_all_page()
    template = get_template('privacy.html')
    return return_request(template, request)